<template>
  <el-dialog :title="$t('common.add')" :visible.sync="dialogVisible" class="el-dialog-normal">
    <div style="margin-bottom: 50px">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="90px" label-position="left" label-suffix=":">
        <el-row :gutter="20">
          <el-col v-for="(item, index) in columns" :key="index" :xs="24" :sm="item.col" :md="item.col" :lg="item.col"
            :xl="item.col">
            <FormComponents :item-obj="item" :form="ruleForm" :isedit="item.edit" @remoteSelectChange="handleChage">
              <template slot="customerType">
                <el-select v-model="ruleForm.customerType" filterable="filterable" remote="remote" clearable="clearable" style="width: 110px;" @change="handlecustomerTypeList">
                  <el-option v-for="item in customerTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
              <template slot="payer">
                <!-- 类型为客户 -->
                <div v-if="ruleForm.customerType === 'CUSTOMER'">
                  <el-select v-model="ruleForm.payer" filterable="filterable" remote="remote" clearable="clearable" style="width: 110px;" @focus="getSummaryList" @change="handleChange">
                    <el-option v-for="item in summaryList" :key="item.customerId" :label="item.customerName" :value="item.customerId" />
                  </el-select>
                </div>
                <!-- 类型为服务商 -->
                <div v-else>
                  {{ ruleForm.payerName }}
                </div>
              </template>
              <template slot="payee">
                <!-- 类型为客户 -->
                <div v-if="ruleForm.customerType === 'CUSTOMER'">
                  {{ ruleForm.payeeName }}
                </div>
                <!-- 类型为服务商 -->
                <div v-else>
                  <el-select v-model="ruleForm.payee" filterable="filterable" remote="remote" clearable="clearable" style="width: 110px;" @focus="getServiceList" @change="handleServiceChange">
                    <el-option v-for="item in serviceList" :key="item.id" :label="item.customerName" :value="item.id" />
                  </el-select>
                </div>
              </template>
            </FormComponents>
          </el-col>
        </el-row>
      </el-form>
      <!-- 查询条件。 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" size="small" label-position="left" class="ry_form">
        <!-- <el-form-item label="财务单类型：" prop="fromType">
          <el-select v-model="queryParams.fromType" filterable="filterable" remote="remote" clearable="clearable" style="width: 110px;">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('fiance.paymentDate')" prop="createTime">
          <!-- <el-date-picker clearable size="small" v-model="queryParams.createTime" type="date"
            placeholder="选择出账日期"> -->
            <el-date-picker
              v-model="statementDate"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="--"
              :start-placeholder="$t('common.beginTime')"
              :end-placeholder="$t('common.deadline')"
              :picker-options="pickerOptions">
            </el-date-picker>
          <!-- </el-date-picker> -->
        </el-form-item>
        <el-form-item class="flex_one tr">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >{{ $t('common.search') }}</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >{{ $t('common.reset') }}</el-button
          >
        </el-form-item>
      </el-form>
      <TableComponents ref="FinanceRef" :url="'/wms/bmsFinanceMain/customerFinanceMainList'" :columns="columnsFinance" :req="{ page: 0, size: 10 }"
        :params="{ customerType: ruleForm.customerType, ...params, ...queryParams }" :methodType="'paramsPost'" :return-data="returnData"
        :maxHeight="'400px'" @selection-change="remoteChange">
        <el-table-column slot="selection" type="selection" align="center" fixed="left" />
      </TableComponents>
    </div>

    <div class="foot-fixed-total">
      <el-button @click="dialogVisible = false">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit('ruleForm')">{{ $t('common.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import dayjs from "dayjs";
import {
  PayType,
  CustomerAccountsReceivable,
} from "@/views/financial/const/index.js";
import {
  summaryList,
} from "@/api/money";
import { customerServiceList } from "@/api/wms/supplier";
import { addBmsBill } from "@/api/money";
import FormComponents from "@/components/FormComponents/index.vue";
import TableComponents from "@/components/Table/list.vue";
import mixTime from '@/views/financial/bill/mixTime.js'
export default {
  components: {
    FormComponents,
    TableComponents,
  },
  mixins: [mixTime],
  data() {
    return {
      rules: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fromType: null,
        createTime: null,
        endTime: null,
        startTime: null
      },
      statementDate: '',
      dialogVisible: false,
      ruleForm: {},
      customerTypeList: [
        { value: 'CUSTOMER', label: this.$t('common.customer') },
        { value: 'SERVICE', label: this.$t('common.facilitator') },
      ],
      columns: [
        { slot: 'customerType', prop: 'customerType', label: this.$t('common.type'), type: 'select', col: 24 },
        // { prop: 'payeeName', label: this.$t('fiance.payee'), type: 'text', col: 12 },
        { slot: 'payee', prop: 'payeeName', label: this.$t('fiance.payee'), type: 'select', col: 12 },
        { slot: 'payer', prop: 'payer', label: this.$t('fiance.drawee'), type: 'select', col: 12 },
        // {
        //   prop: 'payer',
        //   label: this.$t('fiance.drawee'),
        //   col: 12,
        //   type: 'remoteSelect',
        //   selectOptions: {
        //     url: '/wms/bmsFinance/summaryList',
        //     searchStr: 'customerName',
        //     returnStr: '',
        //     data: {},
        //     method: 'POST',
        //     optionsValue: 'customerId',
        //     optionsLabel: 'customerName',
        //     optionsKey: 'customerId'
        //   }
        // }
      ],
      columnsFinance: [
        { slot: "selection" },
        // { prop: "financeNo", label: this.$t('fiance.No'), width: "100px" },
        { prop: "customerName", label: this.$t('customer.name'), width: "100px" },
        { prop: "orderNo", label: this.$t('order.name'), width: "130px" },
        { prop: "mainNo", label: this.$t('fiance.No'), width: "160px" },
        { prop: "payeeAmount", label: this.$t('fiance.receivable'), width: "100px" },
        { prop: "payerAmount", label: this.$t('fiance.copeWith'), width: "100px" },
        // { prop: "typeName", label: this.$t('common.type'), width: "100px" },
        // { prop: "payeeName", label: this.$t('fiance.payeeName'), width: "100px" },
        // { prop: "payerName", label: this.$t('fiance.payerName'), width: "100px" },
        { prop: "createTime", label: this.$t('common.createTime'), width: "140px" },
      ],
      typeList: [
        { value: "DIRECT_RECEIVE", label: '收款' },
        { value: "DIRECT_PAY", label: '付款' },
      ],
      // 客户列表
      summaryList: [],
      // 服务商列表
      serviceList: []
    };
  },
  computed: {
    params() {
      return {
        // customerId: this.ruleForm.payer, status: 'NORMAL'
        /** this.ruleForm.payer客户id  
         * this.ruleForm.payee服务商id */
        customerId: this.ruleForm.customerType === 'CUSTOMER' ? this.ruleForm.payer : this.ruleForm.payee, status: 'NORMAL'
      }
    }
  },
  methods: {
    returnData(data) {
      return data.content.map((r) => {
        r.createTime = dayjs(r.createTime).format("YYYY-MM-DD HH:mm:ss");
        r.typeName = (PayType.find((c) => c.value === r.type) || {}).label;
        r.feeCodeName = (
          CustomerAccountsReceivable.find((t) => t.value === r.feeCode) || {}
        ).label;
        return r;
      });
    },
    handlecustomerTypeList(v) {
      if(v === 'CUSTOMER') {
        this.ruleForm.payee = 109907814893577
        this.ruleForm.payeeName = 'YT'
        this.ruleForm.payer = ''
        this.ruleForm.payerName = ''
      } else if (v === 'SERVICE') {
        this.ruleForm.payer = 109907814893577
        this.ruleForm.payerName = 'YT'
        this.ruleForm.payee = ''
        this.ruleForm.payeeName = ''
      }
      this.getList()
    },
    getSummaryList() {
      const pageReq = { page: 0, size: 10000 }
      const query = { customerName: ''}
      summaryList(query, pageReq).then(res=>{
        this.summaryList = res.content ? res.content : []
      })
    },
    getServiceList() {
      const pageReq = { page: 0, size: 10000 }
      const query = {}
      customerServiceList(query, pageReq).then(res=>{
        this.serviceList = res.content ? res.content : []
      })
    },
    open() {
      this.dialogVisible = true;
      this.ruleForm = {
        // payee: this.$store.state.user.tenantId,
        // payeeName: this.$store.state.user.name,
        // 收款人暂时写死YT
        payee: 109907814893577,
        payeeName: 'YT',
        financeIds: [],
        payer: "",
        payerName: "",
        customerType: 'CUSTOMER'
      };
      // this.getList();
      this.$nextTick(() => {
        this.$refs.FinanceRef.getList();
      });
    },
    submit(formName) {
      if (this.ruleForm.financeIds && this.ruleForm.financeIds.length === 0) {
        return this.$message.error(this.$t('common.chooseOne'));
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveLoading = true;
          // console.log('this.ruleForm', this.ruleForm)
          // return
          const api = addBmsBill;
          api({ ...this.ruleForm })
            .then((r) => {
              this.$message.success(this.$t('common.succcessInfo'));
              this.dialogVisible = false;
              this.saveLoading = false;
              this.$emit("close");
            })
            .catch((e) => {
              this.saveLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    handleChage(obj) {
      if (obj.prop === "payer") {
        if (obj.value && obj.value[0]) {
          this.ruleForm.payerName = obj.value[0].customerName;
          this.getList();
        }
      }
    },
    handleChange(obj) {
      let payerName = this.summaryList.find(item => item.customerId === obj).customerName
      this.ruleForm.payerName = payerName
    },
    handleServiceChange(obj) {
      let payeeName = this.serviceList.find(item => item.id === obj).name
      this.ruleForm.payeeName = payeeName
    },
    remoteChange(row) {
      this.ruleForm.financeIds = row.map((r) => {
        return r.id;
      });
    },
    getList() {
      this.$nextTick(() => {
        this.$refs.FinanceRef.getList();
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.startTime = this.statementDate[0]
      this.queryParams.endTime = this.statementDate[1]
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // this.resetForm("ruleForm");
      this.statementDate = ''
      this.handleQuery();
    },
  },
};
</script>
